<?php

namespace Medicina\KernelBundle\Entity;

use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Entity(repositoryClass="Medicina\KernelBundle\Entity\UserRepository")
 * @ORM\Table(name="admin_user")
 * @ORM\HasLifecycleCallbacks
 */
class User implements UserInterface, \Serializable {

    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length="25", unique=true)
     */
    protected $username;

    /**
     * @ORM\Column(name="password", type="string", length="255")
     */
    protected $password;

    /**
     * @ORM\Column(name="salt", type="string", length="255")
     */
    protected $salt;

    /**
     * @ORM\Column(name="dni", type="string", length=8, unique=true, nullable=true)
     */
    private $dni;

    /**
     * @ORM\Column(name="apellido", type="string", length=50, nullable=true)
     */
    private $apellido;

    /**
     * @ORM\Column(name="nombre", type="string", length=50, nullable=true)
     */
    private $nombre;

    /**
     * @ORM\Column(name="telefono", type="string", length=20, nullable=true)
     */
    private $telefono;

    /**
     * @ORM\Column(name="direccion", type="string", length=30, nullable=true)
     */
    private $direccion;

    /**
     * @ORM\Column(name="codigoPostal", type="string", length=8, nullable=true)
     */
    private $codigopostal;

    /**
     * @ORM\Column(name="email", type="string", length=50, nullable=false)  
     */
    private $email;

    /**
     * se utilizó user_roles para no hacer conflicto al aplicar ->toArray en getRoles()
     * @ORM\ManyToMany(targetEntity="Role", cascade={"persist"})
     * @ORM\JoinTable(name="user_role",
     *     joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
     *     inverseJoinColumns={@ORM\JoinColumn(name="role_id", referencedColumnName="id")}
     * )
     */
    protected $user_roles;

    /**
     * @ORM\ManyToOne(targetEntity="Oficina", inversedBy="usuarios")
     * @ORM\JoinColumn(name="oficina_id", referencedColumnName="id")
     */
    protected $oficina;

    /**
     * @ORM\Column(name="resetpassword", type="boolean", nullable=true)
     */
    private $reset_password;

    
      /**
     * @ORM\Column(name="confirmationToken", type="string", length=255,  nullable=true)
     */
    protected $confirmationToken;
    
    protected $default_user_rol;
            


    public function __construct() {
        $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
        $this->user_roles = new \Doctrine\Common\Collections\ArrayCollection();
    }

    
    public function setDefaultUserRole($role){
            $this->default_user_rol = $role;
    }

    public function getDefaultUserRole(){
            return $this->default_user_rol;
    }


    
      /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpdate() {
        $rol_user = $this->getDefaultUserRole();
        foreach ($rol_user as $r){
        
        print_r($r->getName());
       $this->user_roles[] = $r;
    }
        
    }
    
    
    public function getId() {
        return $this->id;
    }

    /**
     * Set oficina
     *
     * @param Medicina\KernelBundle\Entity\Oficina $oficina
     */
    public function setOficina(\Medicina\KernelBundle\Entity\Oficina $oficina) {
        $this->oficina = $oficina;
    }

    /**
     * Get oficina
     *
     * @return Medicina\KernelBundle\Entity\Oficina 
     */
    public function getOficina() {
        return $this->oficina;
    }

    /**
     * Set dni
     *
     * @param string $dni
     */
    public function setDni($dni) {
        $this->dni = $dni;
    }

    /**
     * Get dni
     *
     * @return string 
     */
    public function getDni() {
        return $this->dni;
    }

    /**
     * Set apellido
     *
     * @param string $apellido
     */
    public function setApellido($apellido) {
        $this->apellido = $apellido;
    }

    /**
     * Get apellido
     *
     * @return string 
     */
    public function getApellido() {
        return $this->apellido;
    }

    /**
     * Set nombre
     *
     * @param string $nombre
     */
    public function setNombre($nombre) {
        $this->nombre = $nombre;
    }

    /**
     * Get nombre
     *
     * @return string 
     */
    public function getNombre() {
        return $this->nombre;
    }

    /**
     * Set telefono
     *
     * @param string $telefono
     */
    public function setTelefono($telefono) {
        $this->telefono = $telefono;
    }

    /**
     * Get telefono
     *
     * @return string 
     */
    public function getTelefono() {
        return $this->telefono;
    }

    /**
     * Set direccion
     *
     * @param string $direccion
     */
    public function setDireccion($direccion) {
        $this->direccion = $direccion;
    }

    /**
     * Get direccion
     *
     * @return string 
     */
    public function getDireccion() {
        return $this->direccion;
    }

    /**
     * Set codigopostal
     *
     * @param string $codigopostal
     */
    public function setCodigopostal($codigopostal) {
        $this->codigopostal = $codigopostal;
    }

    /**
     * Get codigopostal
     *
     * @return string 
     */
    public function getCodigopostal() {
        return $this->codigopostal;
    }

    /**
     * Set username
     *
     * @param string $username
     */
    public function setUsername($username) {
        $this->username = $username;
    }

    /**
     * Get username
     *
     * @return string
     */
    public function getUsername() {
        return $this->username;
    }

    /**
     * Set password
     *
     * @param string $password
     */
    public function setPassword($password) {
        $this->password = $password;
    }

    /**
     * Get password
     *
     * @return string
     */
    public function getPassword() {
        return $this->password;
    }

    /**
     * Set salt
     *
     * @param string $salt
     */
    public function setSalt($salt) {
        $this->salt = $salt;
    }

    /**
     * Get salt
     *
     * @return string
     */
    public function getSalt() {
        return $this->salt;
    }


    public function addRole( $userRoles) {
        $this->user_roles[] = $userRoles;
    }

    public function setUserRoles($roles) {
        $this->user_roles = $roles;
    }

    /**
     * Get user_roles
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getUserRoles() {
        return $this->user_roles;
    }

    /**
     * Get roles
     *
     * @return Doctrine\Common\Collections\Collection
     */
    public function getRoles() {
//        return $this->user_roles->toArray(); //IMPORTANTE: el mecanismo de seguridad de Sf2 requiere ésto como un array
        $roles = array();
        foreach ($this->user_roles as $role) {
            $roles[] = $role->getRole();
        }

        return $roles;
    }

    /**
     * Compares this user to another to determine if they are the same.
     *
     * @param UserInterface $user The user
     * @return boolean True if equal, false othwerwise.
     */
    public function equals(UserInterface $user) {
        return md5($this->getUsername()) == md5($user->getUsername());
    }

    /**
     * Erases the user credentials.
     */
    public function eraseCredentials() {
        
    }

    public static function getRolesSelect() {
        return array('ROLE_ADMIN' => 'ROLE_ADMIN'
            , 'ROLE_PERSONAL' => 'ROLE_PERSONAL'
            , 'ROLE_PROFESORADO' => 'ROLE_PROFESORADO'
            , 'ROLE_DESPACHO' => 'ROLE_DESPACHO'
            , 'ROLE_CONS_DIRECTIVO' => 'ROLE_CONS_DIRECTIVO'
            , 'ROLE_EDITAR_INSCRIPTO' => 'ROLE_EDITAR_INSCRIPTO'
            , 'ROLE_EDITAR_ASESOR' => 'ROLE_EDITAR_ASESOR'
            , 'ROLE_EDITAR_RESOLUCION' => 'ROLE_EDITAR_RESOLUCION'
            , 'ROLE_EDITAR_IMPUGNACION' => 'ROLE_EDITAR_IMPUGNACION'
        );
    }

    public static function getRolesSelectValues() {
        return array_keys(self::getRolesSelect());
    }

  
    public function setEmail($email) {
        $this->email = $email;
    }


    public function getEmail() {
        return $this->email;
    }


    public function setResetPassword($resetPassword) {
        $this->reset_password = $resetPassword;
    }


    public function getResetPassword() {
        return $this->reset_password;
    }

    public function serialize() {
        return serialize(array(
                    $this->id,
                    $this->password,
                    $this->username
                ));
    }

    public function unserialize($serialized) {
        list(
                $this->id,
                $this->password,
                $this->username
                ) = unserialize($serialized);
    }

    public function generateConfirmationToken() {
        if (null === $this->getConfirmationToken()) {
            $this->setConfirmationToken($this->generateToken());
        }
    }

    protected function generateToken() {
        $bytes = false;
        if (function_exists('openssl_random_pseudo_bytes') && 0 !== stripos(PHP_OS, 'win')) {
            $bytes = openssl_random_pseudo_bytes(32, $strong);

            if (true !== $strong) {
                $bytes = false;
            }
        }

        // let's just hope we got a good seed
        if (false === $bytes) {
            $bytes = hash('sha256', uniqid(mt_rand(), true), true);
        }

        return base_convert(bin2hex($bytes), 16, 36);
    }


  
    public function setConfirmationToken($confirmationToken)
    {
        $this->confirmationToken = $confirmationToken;
    }


    public function getConfirmationToken()
    {
        return $this->confirmationToken;
    }
    
}